package com.iot.ammeter.service.impl.web.role;

import com.iot.ammeter.constant.Constant;
import com.iot.ammeter.dto.web.role.RoleDTO;
import com.iot.ammeter.entity.web.role.Role;
import com.iot.ammeter.exception.BusinessExceptions;
import com.iot.ammeter.mapper.web.role.RoleMapper;
import com.iot.ammeter.service.web.role.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.ammeter.utils.SnowFlakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author basil
 * @since 2021-09-25
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper roleMapper;
    private final SnowFlakeIdWorker snowFlakeIdWorker;

    public RoleServiceImpl(RoleMapper roleMapper, SnowFlakeIdWorker snowFlakeIdWorker) {
        this.roleMapper = roleMapper;
        this.snowFlakeIdWorker = snowFlakeIdWorker;
    }

    /**
     * 添加角色
     *
     * @param roleDto 角色信息
     * @return 添加成功或者添加失败
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addRole(RoleDTO roleDto) {
        /**
         * 实体校验
         */
        String roleName = roleDto.getRoleName().trim();
        String description = roleDto.getDescription().trim();
        List<String> authorityList = roleDto.getAuthorityList();
        if (StringUtils.isEmpty(roleName)) {
            throw new BusinessExceptions("角色名称不能空");
        }
        if (StringUtils.isEmpty(description)) {
            throw new BusinessExceptions("角色描述不能空");
        }
        if (authorityList.size() <= 0) {
            throw new BusinessExceptions("角色菜单列表不能为空");
        }
        /**
         * 查询数据库是否已存在该角色
         */
        if (roleMapper.RoleIsExistsByRoleName(roleName) != null) {
            throw new BusinessExceptions("角色已存在");
        }

        Role roleToDb = new Role();
        /**
         * 创建主键id
         */
        String roleId = String.valueOf(snowFlakeIdWorker.nextId());
        roleToDb.setRoleId(roleId);
        roleToDb.setRoleDescription(description);
        roleToDb.setRoleName(roleName);
        roleToDb.setCreateTime(LocalDateTime.now());
        roleToDb.setUpdateTime(LocalDateTime.now());
        roleToDb.setIsDeleted(Constant.Role.NORMAL);
        /**
         * 插入数据库
         */
        int result = roleMapper.insert(roleToDb);
        authorityList.forEach(menuId -> {
            roleMapper.saveRoleAndMenu(String.valueOf(snowFlakeIdWorker.nextId()), roleId, menuId.trim(), LocalDateTime.now(), LocalDateTime.now());
        });
        return result > 0 ? "角色添加成功" : "角色添加失败";
    }

    /**
     * 获取角色列表
     *
     * @param roleName 角色名称，可不携带，不携带查询所有
     * @return 角色列表集合
     */
    @Override
    public List<RoleDTO> getRoleList(String roleName) {
        if (roleName != null) {
            roleName = roleName.trim();
        }
        List<RoleDTO> roleList = roleMapper.selectList(roleName);
        return roleList;
    }

    /**
     * 获取角色详细信息
     *
     * @param roleId 角色id
     * @return ResponseResult
     */
    @Override
    public RoleDTO getRoleDetailById(String roleId) {
        RoleDTO roleDTO = roleMapper.selectOneByRoleId(roleId.trim());
        return roleDTO;
    }

    /**
     * 编辑角色详细信息
     *
     * @param roleId  角色id
     * @param roleDto 角色信息
     * @return 修改成功或者失败提示
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String editRole(String roleId, RoleDTO roleDto) {
        /**
         * 数据校验
         */
        String roleName = roleDto.getRoleName();
        String description = roleDto.getDescription();
        List<String> authorityList = roleDto.getAuthorityList();
        if (StringUtils.isEmpty(roleId)) {
            throw new BusinessExceptions("角色id不能为空");
        }
        if (StringUtils.isEmpty(roleName)) {
            throw new BusinessExceptions("角色名称不能为空");
        }
        if (StringUtils.isEmpty(description)) {
            throw new BusinessExceptions("角色描述不能为空");
        }
        if (authorityList.size() == 0) {
            throw new BusinessExceptions("角色菜单(权限)不能为空");
        }
        /**
         * 1、先删除原有的权限菜单
         * 2、再添加新的
         */
        int result = roleMapper.removeRoleMenuList(roleId);
        authorityList.forEach(menuId -> {
            roleMapper.saveRoleAndMenu(String.valueOf(snowFlakeIdWorker.nextId()), roleId, menuId.trim(), LocalDateTime.now(), LocalDateTime.now());
        });

        /**
         * 查询角色是否存在
         */
        Role roleToDb = roleMapper.selectById(roleId);
        if (roleToDb == null) {
            throw new BusinessExceptions("角色不存在");
        }
        roleToDb.setRoleName(roleName);
        roleToDb.setRoleDescription(description);
        roleToDb.setUpdateTime(LocalDateTime.now());
        result = roleMapper.updateById(roleToDb);

        return result > 0 ? "角色修改成功" : "角色修改失败";
    }
}
